package com.android.aconportable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SIPEngineClient{
	
	private int serverTCPPort;
	private InetAddress serverInetAddr;
	private boolean TCPconnectStatus = false;
	private boolean UDPconnectStatus = false;
	private boolean InetStatus = false;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
	private UDPSocket udpsocket;
	private final static int localPort = 16404;
	private final static int peerPort = 16403;
	
	
	
	public SIPEngineClient(String addr, int port){
		init(addr, port);
	}
	
	private void init(String addr,int port){
		this.serverTCPPort = port;
		try {
			this.serverInetAddr = InetAddress.getByName(addr);
			InetStatus = true;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			InetStatus = false;
		}
	}
	
	public void connect(){
		try {
			socket = new Socket(serverInetAddr, serverTCPPort);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
			sendInviteRequest();
			if(TCPconnectStatus){
				
				
				
				
			}
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			TCPconnectStatus = false;
		} catch (IOException e) {
			e.printStackTrace();
			// TODO Auto-generated catch block
			TCPconnectStatus = false;
		}
		
	}
	
	private void sendInviteRequest(){
		sendMsg("INVITE");
		boolean flag = false;
		String str;
		while(!flag){
			
			try {
				str = in.readLine();
				//System.out.println(str);
				if(str.matches("^200OK"));
					sendMsg("ACK");
				flag = true;
				TCPconnectStatus = true;
				connectUDP();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				TCPconnectStatus = false;
				flag = true;
			}
			
				
		}
	}
	
	public void connectUDP(){
		udpsocket = new UDPSocket(serverInetAddr, peerPort, localPort);
		udpsocket.connect();
		if(udpsocket.isConnect())
			UDPconnectStatus = true;
		else
			UDPconnectStatus = false;
	}
	
	
	
	public boolean isConnect(){
		return TCPconnectStatus && UDPconnectStatus && InetStatus;
	}
	
	private void sendMsg(String str){
		out.println(str);
		out.flush();
	}
	
	public UDPSocket getUdpSocket(){
		return udpsocket;
	}
	
	public void leave() throws IOException{
		
		sendMsg("BYE");
		udpsocket.close();
		in.close();
		out.close();
		socket.close();
	}
}
